package com.bytecub.simulate.device.instance;

import com.bytecub.common.domain.DataResult;
import com.bytecub.common.domain.dto.PageReqDto;
import com.bytecub.common.domain.dto.PageResDto;
import com.bytecub.common.domain.dto.request.DevQueryReqDto;
import com.bytecub.common.domain.dto.response.device.DevicePageResDto;
import com.bytecub.common.domain.dto.response.prop.TemplateResDto;
import com.bytecub.common.enums.BCErrorEnum;
import com.bytecub.common.metadata.ProductFuncTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
  * ByteCub.cn.
  * Copyright (c) 2020-2021 All Rights Reserved.
  * 
  * @author bytecub@163.com  songbin
  * @version Id: HttpDeviceServie.java, v 0.1 2021-01-11  Exp $$
  */
@Service
@Slf4j
public class HttpDeviceService {
    @Autowired com.bytecub.mqtt.domain.config.SimulateHttpProperties httpProperties;
    @Value("${bytecub.mqtt.server.url}")
    String mqttServerUrl;
    @Value("${bytecub.device.http.count}")
    Integer deviceCount;
    @Autowired
    DeviceDemoDataService deviceDemoDataService;
    public List<DeviceInstance> httpGen(){
        List<DeviceInstance> deviceInstances = new ArrayList<>();
        int pageCount = deviceCount/100 + 1;
        int limit = deviceCount > 100 ? 100 : deviceCount;
        List<DevicePageResDto> deviceList = new ArrayList<>();
        for(String productCode: httpProperties.getProductList()){
            for(int i= 0 ; i < pageCount; i++){
                List<DevicePageResDto> list = this.deviceList(i+1, limit, productCode);
                deviceList.addAll(list);
            }
        }


        for(DevicePageResDto item:deviceList){
            TemplateResDto event = deviceDemoDataService.initProductDemo(item.getProductCode(), ProductFuncTypeEnum.EVENT);
            TemplateResDto prop = deviceDemoDataService.initProductDemo(item.getProductCode(), ProductFuncTypeEnum.PROP);
            String productCode = item.getProductCode();
            String deviceCode = item.getDeviceCode();
            String deviceSecret = item.getDeviceSecret();
            DeviceInstance deviceInstance = new DeviceInstance(null,deviceCode, deviceSecret,
                    productCode, mqttServerUrl, event, prop);
            deviceInstance.genClient();
            deviceInstances.add(deviceInstance);
        }
        return deviceInstances;
    }



    private List<DevicePageResDto> deviceList(int pageNo, int limit, String productCode){
        String nonce = RandomStringUtils.randomAlphabetic(10);
        String timestamp = "" + System.currentTimeMillis();
        String uncode = httpProperties.getAppKey() + "|" + nonce + "|" + timestamp + "|" + httpProperties.getAppSecret();
        String sign = DigestUtils.md5DigestAsHex(uncode.getBytes());

        RestTemplate restTemplate = new RestTemplate();
        PageReqDto<DevQueryReqDto> request = new PageReqDto<>();
        request.setLimit(limit);
        request.setPageNo(pageNo);
        DevQueryReqDto devQueryReqDto = new DevQueryReqDto();
        devQueryReqDto.setProductCode(productCode);
        request.setParamData(devQueryReqDto);

        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("key", httpProperties.getAppKey());
        headers.add("nonce", nonce);
        headers.add("timestamp", timestamp);
        headers.add("sign", sign);

        HttpEntity httpEntity =  new HttpEntity<PageReqDto<DevQueryReqDto>>(request, headers);
        ResponseEntity<DataResult<PageResDto<DevicePageResDto>>> responseEntity = restTemplate
                .exchange(httpProperties.getDevUrl(), HttpMethod.POST,httpEntity,
                        new ParameterizedTypeReference<DataResult<PageResDto<DevicePageResDto >>>() {
                        });
        log.info("{}", responseEntity);
        if(responseEntity.getBody().getCode() != BCErrorEnum.SUCCESS.getCode()){
            log.warn("启动HTTP模拟器失败{}", responseEntity);
            System.exit(-1);
        }
        return responseEntity.getBody().getData().getResultData();
    }
}


